﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProjectManagement.Domain.Entities;
using ProjectManagement.Domain.Abstract;
using ProjectManagement.Domain.AutoMappings;
using NHibernate;
using NHibernate.Linq;

namespace ProjectManagement.Domain.Services
{
	public class UserRoleService
	{
		private ISessionFactory factory = NHibernateHelper.CreateSessionFactory();
		//public void Save(UserRole entity)
		//{
		//    throw new NotImplementedException();
		//}

		//public void Remove(UserRole entity)
		//{
		//    throw new NotImplementedException();
		//}

		//public void Update(UserRole entity)
		//{
		//    throw new NotImplementedException();
		//}

		public IEnumerable<UserRole> QueryAll()
		{
			using (var session = factory.OpenSession())
			{
				return session.Query<UserRole>()
					.ToList();
			}
		}

		//public UserRole Get(int id)
		//{
		//    throw new NotImplementedException();
		//}
		public int GetRoleId(int userId)
		{
			using (var session = factory.OpenSession())
			{
				return session.Query<UserRole>()
					.Where(r => r.UserID == userId)
					.FirstOrDefault().RoleID;
			};
		}

		/// <summary>
		/// 返回所有的有权限用户Id列表
		/// </summary>
		/// <returns></returns>
		public IEnumerable<int> AllRoleUserId()
		{
			var list = QueryAll();
			var usrerlist = new List<int>();
			foreach (var item in list)
			{
				usrerlist.Add(item.UserID);
			}
			return usrerlist;
		}

		public UserRole GetUserRoleByUserId(int userId)
		{
			using (var session = factory.OpenSession())
			{
				return session.Query<UserRole>()
					.Where(r => r.UserID == userId)
					.FirstOrDefault();
			}
		}

		public void SaveOrUpdate(UserRole entity)
		{
			var session = factory.OpenSession();
			using (ITransaction trans = session.BeginTransaction())
			{
				session.SaveOrUpdate(entity);
				trans.Commit();
			}
		}

	}
}
